<template>
    <div class="auth">
        <div>
            <auth-group-list :select="true" :sub-height="133" :show-share="false" @data-list="getAuthGroupList" @change="changeAuthGroup"></auth-group-list>
        </div>
        <div class="auth-body">
            <div class="page-action-btn">
                <el-button type="primary" v-if="UIAuth._api_admin_auth_post && tableRow" @click="showAdd(true)">添加子菜单</el-button>
                <el-button type="primary" v-if="UIAuth._api_admin_auth_post" @click="showAdd(false)">添加顶级菜单</el-button>
                <el-button type="warning" v-if="UIAuth._api_admin_auth_put" @click="showEdit">修改</el-button>
                <p-confirm-btn @confirm="del" v-if="UIAuth._api_admin_auth_delete"></p-confirm-btn>
            </div>
            <div v-if="UIAuth._api_admin_auth_get">
                <p-table-tree ref="pTableTree" v-loading="loading" :data="dataList" :sub-height="134" :show-paginate="false" @row-click="rowClick" @row-dblclick="showEdit" @row-clear="rowClear"
                    @selection-change="selectionChange">
                    <el-table-column prop="title" label="名称" min-width="200"></el-table-column>
                    <el-table-column prop="icon" label="图标" width="50">
                        <template v-slot="{row}">
                            <div class="auth-row-icon">
                                <i :class="row.icon"></i>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="img" label="图片" width="50"></el-table-column>
                    <el-table-column prop="route" label="路由" min-width="200"></el-table-column>
                    <el-table-column prop="visit" label="访问权限" min-width="90">
                        <template v-slot="{row}">
                            <div>
                                <api-visit :visit="row.visit"></api-visit>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="auth_type" label="菜单类型" width="80">
                        <template v-slot="{row}">
                            <div>
                                <el-tag v-if="row.auth_type == 1" size="mini">菜单</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="is_show" label="显示" min-width="55">
                        <template v-slot="{row}">
                            <div>
                                <el-tag v-if="row.is_show == 1" size="mini">显示</el-tag>
                                <el-tag v-if="row.is_show == 2" type="info" size="mini">隐藏</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="disabled" label="禁用" min-width="55">
                        <template v-slot="{row}">
                            <div>
                                <el-tag v-if="row.disabled == 1" size="mini">启用</el-tag>
                                <el-tag v-if="row.disabled == 2" type="danger" size="mini">禁用</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sort" label="排序" min-width="80"></el-table-column>
                </p-table-tree>
            </div>
            <p-el-dialog v-model="showDialog" :title="`${isEdit?'修改':'添加'}【${selectAuthGroup && selectAuthGroup.title}】的菜单权限`" width="60%" :height="520" @close="dialogClose"
                @confirm="isEdit?edit():add()" :ok-text="isEdit?'修改':'添加'">
                <el-form :model="params" status-icon :rules="paramsRules" ref="elForm" label-width="120px">
                    <el-form-item label="父菜单 :">{{tableRow?tableRow.title:"顶级"}}</el-form-item>
                    <el-form-item label="所属权限组" prop="auth_group_id">
                        <el-select v-model="params.auth_group_id" placeholder="请选择" @change="addEditSelectAuthGroup">
                            <!--<el-option label="请选择" value=""></el-option>-->
                            <el-option v-for="item in authGroupList" :key="item.id" :label="item.title" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="名称" prop="title">
                        <el-autocomplete style="width:100%" value-key="title" v-model="params.title" :fetch-suggestions="queryRouter" placeholder="请输入或选择菜单名称" @select="selectRouter">
                            <template v-slot="{item}">
                                <div class="auth-autocomplete">
                                    <div>{{item.title}}</div>
                                    <div>{{item.path}}</div>
                                </div>
                            </template>
                        </el-autocomplete>
                    </el-form-item>
                    <el-form-item label="路由">
                        <el-autocomplete style="width:100%" value-key="path" v-model="params.route" :fetch-suggestions="queryRouter" placeholder="请输入或选择菜单路由" @select="selectRouter">
                            <template v-slot="{item}">
                                <div class="auth-autocomplete">
                                    <div>{{item.path}}</div>
                                    <div>{{item.title}}</div>
                                </div>
                            </template>
                        </el-autocomplete>
                    </el-form-item>
                    <div class="phq-from-item2">
                        <div>
                            <el-form-item label="选择图标">
                                <select-icon v-model="params.icon">
                                    <template v-slot="{icon}">
                                        <div>
                                            <i :class="icon"></i>
                                        </div>
                                    </template>
                                </select-icon>
                            </el-form-item>
                        </div>
                        <!--
                        <div>
                            <el-form-item label="图标背景颜色">
                                <el-color-picker v-model="params.icon_color"></el-color-picker>
                            </el-form-item>
                        </div>
                        -->
                    </div>
                    <el-form-item label="访问权限">
                        <el-radio-group v-model="params.visit" size="small">
                            <el-radio-button :label="apiAuth.PUBLIC">{{apiAuthName[apiAuth.PUBLIC]}}</el-radio-button>
                            <el-radio-button :label="apiAuth.LOGIN">{{apiAuthName[apiAuth.LOGIN]}}</el-radio-button>
                            <el-radio-button :label="apiAuth.AUTH">{{apiAuthName[apiAuth.AUTH]}}</el-radio-button>
                            <el-radio-button :label="apiAuth.SYSTEM">{{apiAuthName[apiAuth.SYSTEM]}}</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <div class="phq-from-item3">
                        <div>
                            <el-form-item label="是否显示">
                                <el-radio-group v-model="params.is_show" size="small">
                                    <el-radio-button :label="1">显示</el-radio-button>
                                    <el-radio-button :label="2">隐藏</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                        </div>
                        <div>
                            <el-form-item label="是否禁用">
                                <el-radio-group v-model="params.disabled" size="small">
                                    <el-radio-button :label="1">启用</el-radio-button>
                                    <el-radio-button :label="2">禁用</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                        </div>
                        <div>
                            <el-form-item label="菜单类型">
                                <el-radio-group v-model="params.auth_type" size="small">
                                    <el-radio-button :label="1">菜单</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                        </div>
                    </div>
                    <el-form-item label="默认数据接口">
                        <el-select v-model="params.default_api_list" multiple clearable placeholder="请选择默认数据接口" style="width:100%">
                            <el-option v-for="item in apiList" :key="item.id" :value="item.auth_code" :label="item.title">
                                <div class="auth-select-diy">
                                    <div>{{ item.title }}</div>
                                    <div>{{ item.router }}</div>
                                </div>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数据接口">
                        <el-select v-model="params.api_list" multiple clearable placeholder="请选择数据接口" style="width:100%">
                            <el-option v-for="item in apiList" :key="item.id" :value="item.auth_code" :label="item.title">
                                <div class="auth-select-diy">
                                    <div>{{ item.title }}</div>
                                    <div>{{ item.router }}</div>
                                </div>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input v-model="params.sort" placeholder="排序"></el-input>
                    </el-form-item>
                </el-form>
            </p-el-dialog>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from "vue";
import { useStore } from "vuex";
import { IPaginate, defaultPaginate } from "@/lib/IApp";
import PElDialog from "@/components/PElDialog.vue";
import valid from "@/lib/valid";
import http from "@/lib/http/http";
import PConfirmBtn from "@/components/PConfirmBtn.vue";
import message from "@/lib/message";
import utils from "@/lib/utils";
import AuthGroupList from "@/components/auth/AuthGroupList.vue";
import PTableTree from "@/components/PTableTree.vue";
import SelectIcon from "@/components/SelectIcon.vue";
import config from "@/config";
import routerList from "@/router/routerList";
import TreeTool from "@/lib/TreeTool";
import ApiAuth, { ApiAuthName } from "@/lib/apiRoute/apiRoute";
import ApiVisit from "@/components/api/ApiVisit.vue";
const ParamsRules: any = {
    title: [
        {
            required: true,
            message: "请输入菜单名称",
            trigger: ["blur", "change"],
        },
    ],
};
/**
 * state 数据类型
 */
interface IState {
    loading: boolean;
    dataList: any[]; // 数据列表
    authGroupList: any[]; // 菜单权限组
    paginate: IPaginate; // 分页数据
    showDialog: boolean; // 是否显示 添加编辑窗口
    isEdit: boolean; // 是否修改
    params: any; // http 请求参数
    paramsRules: any; // 参数校验
    tableRow: any; // 单选选择的行内容
    tableRows: any[]; // 多选选择的行内容
    selectAuthGroup: any; // 选择的菜单权限组
    apiList: any[]; // 数据接口
    search: any; // 查询条件
    selectAuthGroupId: string;
}
export default defineComponent({
    name: "Auth",
    components: {
        PElDialog,
        PConfirmBtn,
        AuthGroupList,
        PTableTree,
        SelectIcon,
        ApiVisit,
    },
    setup() {
        const store = useStore();
        const { UIAuth, bodySize } = toRefs(store.state);
        const treeTool: TreeTool = new TreeTool();
        const pTableTree: any = ref<any>();
        const elForm: any = ref<any>();
        const apiAuth = ApiAuth;
        const apiAuthName = ApiAuthName;
        const state = reactive<IState>({
            loading: false,
            dataList: [],
            authGroupList: [],
            paginate: defaultPaginate,
            showDialog: false,
            isEdit: false,
            params: {},
            paramsRules: ParamsRules,
            tableRow: null,
            tableRows: [],
            selectAuthGroup: null,
            apiList: [],
            search: { auth_group_id: "" },
            selectAuthGroupId: "",
        });
        function getLoginUserInfo() {
            store.dispatch("getLoginUserInfo");
        }

        // 获取数据接口
        function getApiList() {
            http.Get(`/api`, { auth_group_id: state.selectAuthGroupId })
                .then((data) => {
                    state.apiList = data;
                })
                .catch((err) => "");
        }
        // 添加修改时选择菜单权限组
        function addEditSelectAuthGroup(val: string) {
            state.selectAuthGroupId = val;
            message.loadingShow();
            getApiList();
        }
        // 获取菜单权限组
        function getAuthGroupList(data: any[]) {
            state.authGroupList = data;
        }
        // 左边列表 选择 菜单权限组
        function changeAuthGroup(val: any) {
            state.dataList = [];
            state.selectAuthGroup = val;
            state.tableRow = null;
            state.tableRows = [];
            pTableTree.value.clearSelect();
            if (val != null) {
                state.selectAuthGroupId = val.id;
                state.search.auth_group_id = val.id;
                getList();
            }
        }
        // 单击选中
        function rowClick(val: any) {
            state.tableRow = val.row;
        }
        // 取消选中
        function rowClear() {
            state.tableRow = null;
        }
        // 关闭添加修改窗口
        function dialogClose() {
            state.params = {};
            state.isEdit = false;
            state.showDialog = false;
        }
        // 多选时触发
        function selectionChange(val: any[]): void {
            state.tableRows = val;
        }
        // 显示添加
        function showAdd(isChile: boolean = true) {
            if (state.selectAuthGroup == null) {
                message.error("请选择【菜单权限组】，再添加菜单");
                return;
            }
            getApiList();
            let pId = "";
            if (isChile) {
                if (state.tableRow == null) {
                    message.error("请选择菜单所属的父菜单");

                    return;
                }
                pId = state.tableRow.id;
            }
            state.params = {
                auth_group_id: state.selectAuthGroup.id,
                pid: pId,
                default_api_list: [],
                api_list: [],
                auth_type: 1,
                visit: apiAuth.LOGIN,
                is_show: 1,
                disabled: 1,
                sort: 1,
            };
            state.isEdit = false;
            state.showDialog = true;
        }
        // 获取内容
        function getList() {
            state.loading = true;
            http.Get(`/auth`, state.search)
                .then((data) => {
                    state.dataList = treeTool.listToTree(data, "");
                    state.loading = false;
                })
                .catch((err) => (state.loading = false));
        }
        // 添加
        function add() {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    http.Post("/auth", state.params)
                        .then((data) => {
                            if (utils.empty(state.dataList)) {
                                state.dataList = [data];
                            } else {
                                treeTool.add(state.dataList, data);
                            }
                            state.params = {};
                            state.showDialog = false;
                            getLoginUserInfo();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        }
        // 选择router
        function queryRouter(queryString: any, callback: any) {
            const arr: any = [];
            routerList.forEach((item: any) => {
                arr.push({
                    path: item.path,
                    title: item.meta.title,
                });
            });
            callback(arr);
        }
        // 选择router
        function selectRouter(val: any) {
            state.params.title = val.title;
            state.params.route = val.path;
        }
        // 显示修改
        function showEdit() {
            if (state.tableRow == null) {
                message.error("请选择要修改的数据");
                return;
            }
            state.selectAuthGroupId = state.tableRow.auth_group_id;
            getApiList();
            state.isEdit = true;
            state.params.title = state.tableRow.title;
            state.params.route = state.tableRow.route;
            state.params.icon = state.tableRow.icon;
            state.params.img = state.tableRow.img;
            state.params.icon_color = state.tableRow.icon_color;
            state.params.visit = state.tableRow.visit;
            state.params.auth_type = state.tableRow.auth_type;
            state.params.default_api_list = state.tableRow.default_api_list;
            state.params.api_list = state.tableRow.api_list;
            state.params.is_show = state.tableRow.is_show;
            state.params.disabled = state.tableRow.disabled;
            state.params.sort = state.tableRow.sort;
            state.params.auth_group_id = state.tableRow.auth_group_id;

            state.params.pid = state.tableRow.pid;
            state.params.id = state.tableRow.id;
            state.params.version = state.tableRow.version;
            state.showDialog = true;
        }
        // 修改
        function edit() {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    http.Put("/auth", state.params)
                        .then((data) => {
                            treeTool.edit(state.dataList, data);
                            dialogClose();
                            getLoginUserInfo();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        }
        // 删除
        function del() {
            const ids: string[] = [];
            if (state.tableRows.length === 0) {
                if (state.tableRow == null) {
                    message.error("请选择要删除的数据");
                    return;
                } else {
                    ids.push(state.tableRow.id);
                }
            }
            let isDelete = true;
            state.tableRows.forEach((item) => {
                if (!utils.empty(item.children) && item.children.length > 0) {
                    isDelete = false;
                    return;
                }
                ids.push(item.id);
            });
            if (!isDelete) {
                message.error("删除的【菜单】中存在子菜单");
                return;
            }
            message.loadingShow("删除中");
            http.Delete("/auth", { ids })
                .then((data) => {
                    treeTool.deletes(state.dataList, ids);
                    state.tableRow = null;
                    state.tableRows = [];
                    pTableTree.value.clearSelect();
                    getLoginUserInfo();
                })
                .catch((err) => "");
        }
        return {
            UIAuth,
            bodySize,
            ...toRefs(state),
            apiAuth,
            apiAuthName,
            routerList,
            pTableTree,
            elForm,
            getList,
            add,
            queryRouter,
            selectRouter,
            showEdit,
            edit,
            del,
            showAdd,
            selectionChange,
            dialogClose,
            rowClear,
            rowClick,
            changeAuthGroup,
            getAuthGroupList,
            addEditSelectAuthGroup,
        };
    },
});
</script>


<style scoped lang="scss">
.auth-row-icon {
    position: absolute;
    top: 3px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 30px;
    height: 30px;
    border-radius: 3px;
    color: #333;
    font-size: 20px;
}
.auth {
    display: flex;
    justify-content: space-between;
    & > div:nth-child(1) {
        width: 240px;
    }
    &-body {
        width: calc(100% - 250px);
    }
    &-select-icon {
        //background-color: $primary-color;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 26px;
        width: 26px;
        border-radius: 3px;
        font-size: 20px;
        //color:#ffffff;
    }
    &-select-diy {
        display: flex;
        align-items: center;
        & > div {
            &:last-child {
                padding-left: 5px;
                font-size: 11px;
                color: #9f9f9f;
            }
        }
    }
    &-autocomplete {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        &:last-child {
            margin-bottom: 5px;
        }
        & > div {
            &:first-child {
                background-color: $primary-color;
                line-height: normal;
                padding: 2px 8px;
                border-radius: 3px;
                color: #ffffff;
            }
            &:last-child {
                margin-left: 10px;
                line-height: normal;
                padding: 2px 8px;
                border-radius: 3px;
                font-size: 12px;
                background-color: $primary-gray;
            }
        }
    }
}
</style>
